package com.webapp.api;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.webapp.helper.HttpUtils;
import com.webapp.helper.MD5Util;
import com.webapp.helper.StringUtil;
import com.webapp.model.OrderInfo;
import com.webapp.model.UserInfo;
import com.webapp.service.OrderInfoService;
import com.webapp.service.UserInfoService;
import com.webapp.view.Resp;


@RestController
public class RoadController extends BaseController{

private static final Logger log = LoggerFactory.getLogger(RoadController.class);
	
	public static final String PAY_URL = "http://ggzf.sh.gov.cn/UnifiedPayWebFront/consume/consumeService.do";
//	public static final String BASE_URL = "http://180.169.37.244/ipms/service/";
	public static final String BASE_URL = "http://ipms.csnits.com/ipms/service/";
	public static final String GET_ADDRESS_KEY_URL = "S_SM_0104";
	public static final String GET_ROAD_PARKING_URL = "S_SM_0109";
	private static final String GET_PAY_KEY_URL = "S_OR_0110";
	private static final String GET_PARK_HISTORY_URL = "S_SM_0107";
	private static final String GET_FEE_ROLE_URL = "S_SM_0106";
	private static final String GET_PRICE_URL = "S_OR_0105";
	private static final String GET_INVOICE_URL = "S_CP_07";
	private static final String GET_ORDER_DETAIL_URL = "S_SM_0108";
	private static final String GET_ORDER_TRADE_URL = "S_SM_0110";
	private static final String INSERT_ORDER_TRADE_URL = "S_OR_0112";
	private static final String CN_PAY_KEY = "303110100000340";
	private static final String JA_PAY_KEY = "303110600000292";
	private static final String UPDATE_TRADE_URL = "S_OR_0121";
	
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private UserInfoService userInfoService;
	
	/**
	 * 更新交易记录
	 * @param tradeNo
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value  = "/1road/data/saveTrade")
	public Resp saveTrade(String orderNo,String orderno,String amount,String payHours,HttpServletRequest req){
		Resp resp = new Resp(false);
		String ip = getClientIp(req);
		try {
			log.warn("amount:{},payHours:{}",amount,payHours);
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtil.isBlank(amount)||"null".equals(amount)) {
				amount = "0";
			}
			data.put("tradeNo", orderno);
			data.put("orderNo", orderNo);
			data.put("parkingHours", payHours);
			data.put("payMoney", Double.valueOf(amount)*100);
			data.put("payMethod", "wechat");
			data.put("tradeTime", sdf.format(new Date()));
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+UPDATE_TRADE_URL,json );
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e 出错了 ip:{}",ip);
		}
		return resp;
	}
	
	/**
	 * 获取发票链接
	 * @param tradeNo
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getInvoiceUrl")
	public Resp getInvoiceUrl(String tradeNo,String carLicense){
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("tradeNo", tradeNo);
			data.put("carlicense", carLicense);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_INVOICE_URL,json );
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	@RequestMapping(value = "/1road/data/getPayInfo")
	public Resp getPayInfo(String orderNo,String orderType,String amount,String month,HttpServletRequest req){
		Resp resp = new Resp(false);
		String ip = getClientIp(req);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			Map<String, Object> payMap = new HashMap<String, Object>();
			Map<String, Object> responseMap = new HashMap<String, Object>();
			data.put("orderNo", orderNo);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_ORDER_DETAIL_URL,json );
			JSONObject detailJson = JSONObject.parseObject(res);
			if(detailJson!=null) {
				JSONObject detailAttr =  detailJson.getJSONObject("attr");
				if(detailAttr!=null) {
					JSONArray detailArr = detailAttr.getJSONArray("result");
					JSONObject detail = detailArr.getJSONObject(0);
					String appId = detail.getString("appId");
					String loginName = detail.getString("inputter");
					String simId = detail.getString("simId");
					String cph = detail.getString("carLicense");
					String streetNo = detail.getString("parkingNo");
					String reqKey = CN_PAY_KEY;
					if(appId.equals("GGZF_APPID")) {
						reqKey = JA_PAY_KEY;
					}
					Double am = Double.valueOf(amount);
					String key = getKey(reqKey);
					if(amount==null) {
						am =  detail.getDoubleValue("totalAmount")- detail.getDoubleValue("havePayMoney");//0.01;//;
					}
					Map<String, Object> tradeMap = new HashMap<String, Object>();
					tradeMap.put("orderNo", orderNo);
					tradeMap.put("totalAmount", String.valueOf(amount));
					tradeMap.put("loginName", loginName);
					tradeMap.put("simId", simId);
					tradeMap.put("orderType", String.valueOf(orderType));
					DecimalFormat df = new DecimalFormat("#.00");
					tradeMap.put("parkingHours", df.format(detail.getDoubleValue("parkingTime")/60));
					map.put("attr", tradeMap);
					json = JSONObject.toJSONString(map);
					res = HttpUtils.postJson(BASE_URL+INSERT_ORDER_TRADE_URL,json );
					String tradeNo = JSONObject.parseObject(res).getJSONObject("attr").getString("tradeNo");
					payMap.put("version", "1.0");
					payMap.put("appid", reqKey);
					payMap.put("order_no", tradeNo);
					payMap.put("amount", String.valueOf(new Double(am).intValue()*100) );
					payMap.put("subject", "2");
					payMap.put("pay_type", "02");
					payMap.put("return_url", "https://h5.csnits.com/park/r_orderDetail");
					payMap.put("nocredit", "1");
					payMap.put("timeout", "60m");
					String reqSign = "|"+String.valueOf(new Double(am).intValue()*100)+"|"+reqKey+"|"+tradeNo+"|"+key+"|";
					String sign = MD5Util.toMD5(reqSign).toUpperCase();
					log.warn("=====>reqSign:{},sign:{}",reqSign,sign);
					payMap.put("sign", sign);
					responseMap.put("park", tradeMap);
					responseMap.put("pay", payMap);
					OrderInfo order = orderInfoService.getByOrderNo(orderNo);
					if(order==null) {
						order = new OrderInfo();
						order.setCph(cph);
						order.setCreateTime(new Date());
						order.setOutNo(tradeNo);
						order.setOrderNo(orderNo);
						order.setPay(String.valueOf(am));
						order.setStreetNo(streetNo);
						order.setType(2);
						order.setMonth(month);
						orderInfoService.save(order);
					}else {
						order.setPay(String.valueOf(am));
						order.setOutNo(tradeNo);
						order.setMonth(month);
						orderInfoService.update(order);
					}
				}
				
			}
			return new Resp(responseMap);
		} catch (Exception e) {
			log.error("e 支付信息出错了:{}",ip);
		}
		return resp;
	}
	
	/**
	 * 获取发票链接
	 * @param tradeNo
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getTrade")
	public Resp getTrade(String orderNo){
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("orderNo", orderNo);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_ORDER_TRADE_URL,json );
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	/**
	 * 获取订单详情
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getOrderDetail")
	public Resp getOrderDetail(String orderNo ,HttpServletRequest req){
		String ip = getClientIp(req);
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("orderNo", orderNo);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_ORDER_DETAIL_URL,json );
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e 订单详情出错了:{}",ip);
		}
		return resp;
	}
	
	/**
	 * 计算应交多少钱
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getPrice")
	public Resp getPrice(String beginTime,String time,String parkingNo,String orderNo ){
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			data.put("bTime",beginTime);
			data.put("parkingNo", parkingNo);
			String eTime = sdf.format(sdf.parse(beginTime).getTime()+Long.valueOf((long) (Double.valueOf(time)*3600*1000)));
			data.put("eTime", eTime);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_PRICE_URL,json );
			JSONObject obj = JSONObject.parseObject(res);
			String attr = obj.getString("attr");
			Double amount = JSONObject.parseObject(attr).getDouble("amount");
			Map<String,Object> map2 = new HashMap<String, Object>();
			Map<String,Object> data2= new HashMap<String, Object>();
			data2.put("orderNo", orderNo);
			map2.put("attr", data2);
			String json2 = JSONObject.toJSONString(map2);
			String res2 = HttpUtils.postJson(BASE_URL+GET_ORDER_DETAIL_URL,json2 );
			JSONObject obj2 = JSONObject.parseObject(res2);
			JSONArray arr = obj2.getJSONObject("attr").getJSONArray("result");
			JSONObject obj3 = arr.getJSONObject(0);
			Double havePay = obj3.getDouble("havePayMoney");
			return new Resp(amount-havePay);
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	/**
	 * 获取计费规则
	 * @param streetNo
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getFeeRole")
	public Resp getFellRole(String streetNo) {
		Resp resp = new Resp(false);
		try {
			Map<String, String> map = new HashMap<String, String>();
			Map<String, Object> data = new HashMap<String, Object>();
			if (StringUtil.isBlank(streetNo)) {
				streetNo = "JAZ028";
			}
			map.put("streetNo", streetNo);
			data.put("attr", map);
			String result = HttpUtils.postJson(BASE_URL + GET_FEE_ROLE_URL, JSONObject.toJSONString(data));
			JSONObject jsonObject = JSONObject.parseObject(result);
			JSONObject attr = jsonObject.getJSONObject("attr");
			JSONArray res = attr.getJSONArray("result");
			String htmlStr = "";
			if(res!=null) {
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("workday".equals(obj.getString("dateType"))) {
						if("0".equals(obj.getString("period"))) {
							htmlStr+= "<p>1、工作日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="首小时："+obj.getString("firstHourMoney")+"元;后续每半小时："+obj.getString("unitPrice")+"元;</p>";
						}
					}
				}
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("workday".equals(obj.getString("dateType"))) {
						if(!"0".equals(obj.getString("period"))) {
							htmlStr+= "<p>2、工作日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="收费金额："+obj.getString("period")+"元</p>";
						}
					}
				}
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("weekday".equals(obj.getString("dateType"))) {
						if("0".equals(obj.getString("period"))) {
							htmlStr+= "<p>3、双休日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="首小时："+obj.getString("firstHourMoney")+"元;后续每半小时："+obj.getString("unitPrice")+"元;</p>";
						}
					}
				}
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("weekday".equals(obj.getString("dateType"))) {
						if(!"0".equals(obj.getString("period"))) {
							htmlStr+= "<p>4、双休日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="收费金额："+obj.getString("period")+"元</p>";
						}
					}
				}
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("holiday".equals(obj.getString("dateType"))) {
						if("0".equals(obj.getString("period"))) {
							htmlStr+= "<p>5、节假日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="首小时："+obj.getString("firstHourMoney")+"元;后续每半小时："+obj.getString("unitPrice")+"元;</p>";
						}
					}
				}
				for(int i = 0;i<res.size();i++) {
					JSONObject obj = res.getJSONObject(i);
					if("holiday".equals(obj.getString("dateType"))) {
						if(!"0".equals(obj.getString("period"))) {
							htmlStr+= "<p>6、节假日："+obj.getString("okMoneyInputStart")+"~"+obj.getString("okMoneyInputEnd")+",";
							htmlStr+="收费金额："+obj.getString("period")+"元</p>";
						}
					}
				}
			}
			
			return new Resp(htmlStr);
		} catch (Exception e) {
			log.error("error:{}",e);
		}
		return resp;
	}
	
	
	/**
	 * 查询路侧车牌历史停车记录
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getRoadParkHistory")
	public Resp getRoadParkHistory(String carLicense){
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("carLicense", carLicense);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_PARK_HISTORY_URL,json );
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	/**
	 * 查询路侧在停车辆
	 * @param carLicense
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getRoadParking")
	public Resp getRoadParking(String carLicense,String openid){
		Resp resp = new Resp(false);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("carLicense", carLicense);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_ROAD_PARKING_URL,json );
			String attr = JSONObject.parseObject(res).getString("attr");
			if(StringUtil.isNotBlank(attr)) {
				JSONObject attrObj = JSONObject.parseObject(attr);
				JSONArray arr = JSONObject.parseArray(attrObj.getString("result"));
				if(arr!=null&&arr.size()>0) {
					JSONObject obj = arr.getJSONObject(0);
					String streetNo = obj.getString("streetNo");
					UserInfo user = userInfoService.findBySAndOAndC(openid, carLicense, streetNo, 2);
					if(user==null) {
						user = new UserInfo();
						user.setCph(carLicense);
						user.setStreetNo(streetNo);
						user.setOpenid(openid);
						user.setType(2);
						user.setCreateTime(new Date());
						userInfoService.save(user);
					}else {
						user.setCreateTime(new Date());
						userInfoService.update(user);
					}
				}
			}
			return new Resp(JSONObject.parse(res));
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	/**
	 * 根据关键字查询场库
	 * @param key
	 * @return
	 */
	@RequestMapping(value = "/1road/data/getAddressByKey")
	public Resp getAddressByKey(String key){
		Resp resp = new Resp(false);
		try {
			if(StringUtil.isBlank(key)) {
				key = "延平路";
			}
			Map<String,Object> map = new HashMap<String, Object>();
			Map<String,Object> data = new HashMap<String, Object>();
			data.put("streetName", key);
			map.put("attr", data);
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_ADDRESS_KEY_URL,json );
			return new Resp(JSONObject.parseObject(res));
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return resp;
	}
	
	public static String getKey(String key) {
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			String json = JSONObject.toJSONString(map);
			String res = HttpUtils.postJson(BASE_URL+GET_PAY_KEY_URL,json );
			JSONObject obj = JSONObject.parseObject(res).getJSONObject("attr");
			if(key.equals(JA_PAY_KEY)) {
				return obj.getString("ggzfWorkKey");
			}else {
				return obj.getString("ggzfWorkKey_cn");
			}
		} catch (Exception e) {
			log.error("e:{}",e);
		}
		return "3b6DytPqMzBkdReT8E4IgQV9ZlAHXGgh";
	}
	
}
